<template>
  <div class="ScrollContainer" id="switchBar">
    <div :class="['switchBar', isTop ? 'scrollTop' : ''].join(' ')">
      <div class="switchItem" @click="handleBarclick('one')">任务一</div>
      <div class="switchItem" @click="handleBarclick('two')">任务二</div>
      <div class="switchItem" @click="handleBarclick('three')">任务三</div>
    </div>
    <ul class="ulContainer">
      <div v-for="({name, id}) in list" :key="id" class="liItem">{{name}}</div>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'scrollTopAndOffsetTop',
  data() {
    return {
      list: [],
      isTop: false,
      activeBar: 'one',
    }
  },
  created() {
    let list = [];
    for(let i = 0; i < 50; i += 1) {
      list.push({ name: `list${i}`, id: i});
    }
    this.list = list;
  },
  methods: {
    test() {
      let switchBar = window.document.getElementById('switchBar');
      let offSetTop = switchBar.offsetTop;
      console.log('offSetTop', offSetTop);
      let win = window.document;
      let scrollTop = win.documentElement.scrollTop || win.body.scrollTop;
      console.log('scrollTop', scrollTop);
      if (offSetTop <= scrollTop) {
        this.isTop = true;
      } else {
        this.isTop = false;
      }
    },
    handleIdchange() {
      console.log('ID', this.activeBar);
    },
    handleBarclick(val) {
      this.activeBar = val;
    },
    listenScreenVisible() {
      console.log('123', document.visibilityState);
      document.addEventListener('visibilitychange', () => {
        // eslint-disable-next-line 
        if (document.visibilityState == 'visible') {
          console.log('页面可见了');
        }
      })
    }
  },
  mounted() {
    // 获取指定元素
    // const scrollview = window.document.getElementById('switchBar');
    // scrollview.addEventListener('scroll', this.addEventListener, true);
    // console.log('this addEventListener', this.test, scrollview);
    // scrollview.addEventListener('scroll', this.test, true)
    // scrollview.addEventListener('scroll', this.test);
    console.log('MOUNT');
    // 监听整个屏幕滚动
    window.onscroll = this.test;
    // 监听屏幕是否可见
    this.listenScreenVisible();
  },
  beforeUpdate() {
    console.log('beforeUpdate');
  },
  updated() {
    console.log('update');
  },
  watch: {
    activeBar(ne, old) {
      this.handleIdchange();
      console.log('idchange', old, ne);
    }
  },
}
</script>

<style lang="scss" scoped src='./index.scss'>

</style>